package test;


import cn.yunhe.model.Books;
import cn.yunhe.model.Categories;
import cn.yunhe.model.Orderbook;
import cn.yunhe.model.Orders;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;


import java.util.List;

public class test1 {
    Session session;
    Transaction transaction;

    @Before
    public void  init(){
       Configuration configuration = new Configuration().configure();
       SessionFactory sessionFactory = configuration.buildSessionFactory();
       session = sessionFactory.openSession();
       transaction = session.beginTransaction();
    }

    @Test
    public void test1(){
      Books books = (Books) session.get(Books.class,1);
        System.out.println(books.getAuthor());
    }

    @Test
    public  void test2(){
       // List<Books>  booksList = session.createSQLQuery("select {b.*} from Books b").addEntity("b",Books.class).list();
        List<Books> list = session.createSQLQuery("select {b.*} from books b").addEntity("b", Books.class).list();
        System.out.println(list.size());
    }
   @Test
    public void test(){
             List<Object[]> list = session.createSQLQuery(" select {b.*},{c.*} from books b ,categories c where b.categoryid = c.id")
                .addEntity("b", Books.class).
                        addEntity("c", Categories.class).
                        list();
//       List<Object[]> list = session.getNamedQuery("mySqlNamedQuery").list();


       for (Object[] objs : list) {
           Books books = (Books) objs[0];
           Categories categories = (Categories) objs[1];

           System.out.println(books.getTitle() + "," + books.getCategories().getName());
       }
    }

    @Test
    public void test4() {
        Query query = session.getNamedQuery("myNamedQuery");
        query.setString("title", "%做法%");
        query.setDouble("price", 150);

        List<Books> bookList = query.list();
        for (Books b :
                bookList) {
            System.out.println(b.getTitle() + "," + b.getPrice());
        }
    }

    @After
    public  void dest(){
        transaction.commit();
        session.close();
    }

}
